<template>
  <div class="tags-view">
    <div class="tags-scroll">
      <el-tag
        v-for="tag in tagsViewStore.visitedViews"
        :key="tag.path"
        :type="tag.path === route.path ? 'primary' : 'info'"
        :effect="tag.path === route.path ? 'dark' : 'plain'"
        closable
        @close="onClose(tag)"
        class="tag-item"
      >
        <span @click="go(tag.path)" class="tag-text">{{ tag.title }}</span>
      </el-tag>
    </div>
    <el-dropdown trigger="click">
      <el-button text class="more-btn">标签</el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="closeOthers">关闭其它</el-dropdown-item>
          <el-dropdown-item @click="closeAll">关闭全部</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTagsViewStore } from '@/stores/tagsView'

const route = useRoute()
const router = useRouter()
const tagsViewStore = useTagsViewStore()

const addTag = () => {
  if (route.meta && route.meta.title) {
    tagsViewStore.addVisitedView(route)
  }
}

onMounted(() => {
  addTag()
})

watch(() => route.fullPath, () => addTag())

const onClose = (tag) => {
  // 防止关闭固定标签
  if (tag.affix) return
  tagsViewStore.delVisitedView(tag)
  if (route.path === tag.path) {
    // 如果关闭的是当前标签，跳转到最后一个
    const last = tagsViewStore.visitedViews[tagsViewStore.visitedViews.length - 1]
    if (last) router.push(last.path)
    else router.push('/home')
  }
}

const go = (path) => {
  if (path !== route.path) router.push(path)
}

const closeOthers = () => {
  tagsViewStore.delOthersViews(route.path)
}

const closeAll = () => {
  tagsViewStore.delAllViews()
  router.push('/home')
}
</script>

<style scoped>
.tags-view {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 12px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.tags-scroll {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
}

.tag-text {
  padding: 0 2px;
}

.more-btn {
  color: #909399;
}

.dark .tags-view {
  background: #1f1f1f;
  border-bottom-color: #2b2b2b;
}
</style>


